package com.shuimin.service;

import com.shuimin.service.model.customer_service.SurveyAnswer;
import com.shuimin.service.model.customer_service.SurveyTemp;
import com.shuimin.service.model.customer_service.SurveyTempDetail;
import com.shuimin.service.model.customer_service.VSurveyTempDetail;
import pond.common.S;
import pond.db.Record;
import pond.db.sql.Criterion;
import pond.db.sql.Sql;
import pond.db.sql.SqlSelect;
import pond.web.Render;
import pond.web.Router;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static pond.db.sql.Sql.selectFromRequest;

/**
 * Created by sky on 2017/6/6.
 */
public class SURVEY_TEMP extends Router {
    {

        get("/search", (req, resp) -> App.DB.post(t -> {
            SqlSelect sqlSelect = selectFromRequest(req.toMap(), SurveyTemp.class);
            resp.render(Render.page(
                    S._for(
                            t.query(SurveyTemp.class, sqlSelect))
                            .map(SurveyTemp::view)
                            .toList(),
                    t.count(sqlSelect.count())));
        }));

        get("/temp/:id",(req,resp)->{
            String id=req.paramNonBlank("id","temp_id can not be null");
            SurveyTemp temp=App.DB.get(t -> t.recordById(SurveyTemp.class, id));
            SqlSelect detail_sql= Sql.select("*").from(VSurveyTempDetail.class);
            detail_sql.where("main_id",Criterion.EQ,id);
            detail_sql.orderBy("sn asc");
            List<VSurveyTempDetail> list=App.DB.get(t->t.query(VSurveyTempDetail.class, detail_sql));

            Map<String,Object> map=new HashMap<>();
            map.put("content", temp);
            App.DB.post(t -> {
                map.put("detail", S._for(list).map(item -> {
                    SqlSelect aSql=Sql.select("*").from(SurveyAnswer.class);
                    aSql.where("question_id",Criterion.EQ,item.get("question_id"));
                    aSql.orderBy("sn asc");
                    List<SurveyAnswer> answer=t.query(SurveyAnswer.class, aSql);
                    item.set("answers",answer);
                    return item;
                }).toList());
            });

            resp.render(Render.json(map));
        });

        post("/create_temp", (req, resp) -> {
            SurveyTemp st = (SurveyTemp) Record.newEntity(SurveyTemp.class).merge(req.toMap());
            App.DB.post(t -> t.recordInsert(st));
            resp.render(Render.json(st));
        });

        post("/create_temp_detail/:temp_id", (req, resp) -> {
            String temp_id = req.paramNonBlank("temp_id", "temp_id can not be null");
            SurveyTempDetail std = (SurveyTempDetail) Record.newEntity(SurveyTempDetail.class).merge(req.toMap());
            std.set("main_id", temp_id);
            App.DB.post(t -> t.recordInsert(std));
            resp.send(200);
        });

    }

}
